/**
 * @description 验证码 - Yuanr
 * @param {Number} time - 倒计时时长
 * @param {Function} onStart - 点击验证码按钮并对手机号进行校验， 通过返回true, 失败false
 * @param {Object} style - 自定义样式， 所有样式都可以覆盖
 */
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class VerificationCode extends Component {
  constructor(props) {
    super(props);
    const { time } = this.props;
    this.state = { second: time || 60, start: false }; // 获取验证码时间间隔
    this.timer = null; // 验证器 计时器返回id
    this.getCode = this.getCode.bind(this);
  }

  getCode() {
    const { time, onStart } = this.props;
    clearInterval(this.timer);
    this.setState(() => ({ second: time || 60 }));
    //  开始倒计时，并检查号码是否符合
    if (onStart && onStart()) {
      this.setState(() => ({ start: true }));
      this.timer = setInterval(() => {
        const { second } = this.state;
        if (second === 0) {
          clearInterval(this.timer);
          //  结束倒计时
          this.setState(() => ({
            second: time || 60,
            start: false
          }));
        }
        this.setState(previousState => ({ second: previousState.second - 1 }));
      }, 1000);
    }
  }

  render() {
    let html = '';
    const { start, second } = this.state;
    const { style } = this.props;
    if (start) {
      html = <Text style={[styles.yanz, style]}>{second}s后重试</Text>;
    } else {
      html = (
        <Text style={[styles.yanz, style]} onPress={this.getCode}>
          获取验证码
        </Text>
      );
    }
    return <View>{html}</View>;
  }
}

const styles = StyleSheet.create({
  yanz: {
    width: 110,
    height: SCALE(76),
    lineHeight: SCALE(76),
    backgroundColor: '#044e8d',
    textAlign: 'center',
    color: '#fff'
  }
});
